package com.rlf.sf.legacymapping.xml;

import com.rlf.sf.legacymapping.xml.object.RootLegacyPermissionMapping;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.security.AnyTypePermission;

public class XmlUtil {
	private static String XML_TAG = "<?xml version='1.0' encoding='UTF-8'?> \n\n";
	public static String toXmlMessage(RootLegacyPermissionMapping bean) {
		final XStream xstream = new XStream(new DomDriver());
		xstream.processAnnotations(bean.getClass());
		return xstream.toXML(bean);
	}
	
	public static String toXmlMessageWithTag (RootLegacyPermissionMapping bean) {
		return XML_TAG + toXmlMessage(bean);
	}


	private static XStream getInstance() {
		XStream xStream = new XStream(new DomDriver("UTF-8")) {
			@Override
			protected MapperWrapper wrapMapper(MapperWrapper next) {
				return new MapperWrapper(next) {
					@SuppressWarnings("rawtypes")
					@Override
					public boolean shouldSerializeMember(Class definedIn, String fieldName) {
						if (definedIn == Object.class) {
							return false;
						}
						return super.shouldSerializeMember(definedIn, fieldName);
					}
				};
			}
		};

		xStream.setClassLoader(XmlUtil.class.getClassLoader());
		xStream.addPermission(AnyTypePermission.ANY);
		return xStream;
	}

	public static <T> T xmlToBean(String xml, Class<T> clazz) {
		XStream xStream = getInstance();
		xStream.processAnnotations(clazz);
		Object object = xStream.fromXML(xml);
		T cast = clazz.cast(object);
		return cast;
	}

	public static String beanToXml(Object object) {
		XStream xStream = getInstance();
		xStream.processAnnotations(object.getClass());
		String xml = xStream.toXML(object).replaceAll("\\s+", " ");
		return xml;
	}

	public static String beanToXmlWithTag(Object object) {
		String xml = XML_TAG + beanToXml(object);
		return xml;
	}
}
